package com.sxhuayuan.parking.controller;

import java.util.Date;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import com.sxhuayuan.parking.compenent.Message;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import com.sxhuayuan.parking.compenent.editor.DateEditor;
import com.sxhuayuan.parking.compenent.web.RespMessage;
import com.sxhuayuan.parking.config.Platform;
import com.sxhuayuan.parking.utils.SpringUtils;

public class BaseController {

	@Resource(name = "validator")
	private Validator validator;

	/** "验证结果"参数名称 */
	private static final String CONSTRAINT_VIOLATIONS_ATTRIBUTE_NAME = "constraintViolations";

	/**
	 * 数据绑定
	 * 
	 * @param binder
	 *            WebDataBinder
	 */
	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
		binder.registerCustomEditor(Date.class, new DateEditor(true));
	}

	/**
	 * 数据验证
	 * 
	 * @param target
	 *            验证对象
	 * @param groups
	 *            验证组
	 * @return 验证结果
	 */
	protected boolean isValid(Object target, Class<?>... groups) {
		Set<ConstraintViolation<Object>> constraintViolations = validator.validate(target, groups);
		if (constraintViolations.isEmpty()) {
			return true;
		} else {
			RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
			requestAttributes.setAttribute(CONSTRAINT_VIOLATIONS_ATTRIBUTE_NAME, constraintViolations, RequestAttributes.SCOPE_REQUEST);
			return false;
		}
	}

	protected Set<ConstraintViolation<Object>> getValidInfo() {
		RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
		return (Set<ConstraintViolation<Object>>) requestAttributes.getAttribute(CONSTRAINT_VIOLATIONS_ATTRIBUTE_NAME, RequestAttributes.SCOPE_REQUEST);
	}

	public RespMessage getValidErrorInfo() {
		StringBuilder info = new StringBuilder();
		for (ConstraintViolation<Object> c : getValidInfo()) {
			info.append(c.getPropertyPath()).append(SpringUtils.getMessage(c.getMessage())).append("; ");
		}
		return RespMessage.error("表单验证失败: " + info.toString());
	}

	protected Platform getPlatform(HttpServletRequest request) {
		return null;
	}

	protected RespMessage successResp(Object datas) {
		return RespMessage.builder().success().setDatas(datas).build();
	}

	/** 登录超时统一返回错误信息 */
	protected RespMessage invalidToken() {
		return RespMessage.error(RespMessage.Status.INVALID_TOKEN, Message.LOGIN_INVALID_TOKEN);
	}
}
